{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "view-in-github"
      },
      "source": [
        "\u003ca href=\"https://colab.research.google.com/github/google/neural-tangents/blob/master/notebooks/myrtle_kernel_with_neural_tangents.ipynb\" target=\"_parent\"\u003e\u003cimg src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/\u003e\u003c/a\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cIkq2O7yVWYJ"
      },
      "source": [
        "Copyright 2020 Google LLC\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "You may obtain a copy of the License at\n",
        "\n",
        "     https://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and\n",
        "limitations under the License."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "K93Gf2UZrorh"
      },
      "outputs": [],
      "source": [
        "# Install Neural Tangents Library\n",
        "!pip install -q git+https://www.github.com/google/neural-tangents"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "ZxPII0eszjDR"
      },
      "outputs": [],
      "source": [
        "# Check which device you are running  before benchmarking\n",
        "# For examples V100 can perform 40x double precision flops compared to P4\n",
        "!nvidia-smi --query-gpu=gpu_name,driver_version,memory.total --format=csv"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "0b4mR5IksABN"
      },
      "outputs": [],
      "source": [
        "from jax.config import config\n",
        "# Enable float64 for JAX\n",
        "config.update(\"jax_enable_x64\", True)\n",
        "\n",
        "import jax.numpy as np\n",
        "from jax import jit\n",
        "import functools\n",
        "from jax import random\n",
        "\n",
        "import neural_tangents as nt\n",
        "from neural_tangents import stax\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "q2A94cEmtGOE"
      },
      "outputs": [],
      "source": [
        "key = random.PRNGKey(0)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "KZAhaHn7sLtN"
      },
      "outputs": [],
      "source": [
        "# Network architecture described in \n",
        "# Shankar et al., Neural Kernels Without Tangents, 2020.\n",
        "# https://arxiv.org/abs/2003.02237\n",
        "\n",
        "def MyrtleNetwork(depth, W_std=np.sqrt(2.0), b_std=0.):\n",
        "  layer_factor = {5: [2, 1, 1], 7: [2, 2, 2], 10: [3, 3, 3]}\n",
        "  width = 1\n",
        "  activation_fn = stax.Relu()\n",
        "  layers = []\n",
        "  conv = functools.partial(stax.Conv, W_std=W_std, b_std=b_std, padding='SAME')\n",
        "  \n",
        "  layers += [conv(width, (3, 3)), activation_fn] * layer_factor[depth][0]\n",
        "  layers += [stax.AvgPool((2, 2), strides=(2, 2))]\n",
        "  layers += [conv(width, (3, 3)), activation_fn] * layer_factor[depth][1]\n",
        "  layers += [stax.AvgPool((2, 2), strides=(2, 2))]\n",
        "  layers += [conv(width, (3, 3)), activation_fn] * layer_factor[depth][2]\n",
        "  layers += [stax.AvgPool((2, 2), strides=(2, 2))] * 3\n",
        "\n",
        "  layers += [stax.Flatten(), stax.Dense(10, W_std, b_std)]\n",
        "\n",
        "  return stax.serial(*layers)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "-2CJp5wysyvm"
      },
      "outputs": [],
      "source": [
        "_, _, ker_fn = MyrtleNetwork(5)\n",
        "ker_fn = jit(ker_fn, static_argnums=(2,))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "8df1GkZws48V"
      },
      "outputs": [],
      "source": [
        "key1, key2 = random.split(key)\n",
        "input_x1 = random.normal(key1, shape=(10, 32, 32, 3))\n",
        "input_x2 = random.normal(key2, shape=(10, 32, 32, 3))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "colab": {
          "height": 35
        },
        "colab_type": "code",
        "executionInfo": {
          "elapsed": 3712,
          "status": "ok",
          "timestamp": 1587514330269,
          "user": {
            "displayName": "",
            "photoUrl": "",
            "userId": ""
          },
          "user_tz": 420
        },
        "id": "ApQ2j8F2yvZ5",
        "outputId": "5e9ef30f-a007-4397-ec00-a6cbb314141d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "1 loops, best of 3: 35.7 ms per loop\n"
          ]
        }
      ],
      "source": [
        "# Note that library computes the full matrix thus lead to 2x inefficiency.\n",
        "# With custom batching, only compute upper triangles.\n",
        "# First loop during timing run includes jit compilation time and maybe slower.\n",
        "%%timeit\n",
        "kdd = ker_fn(input_x1, None, 'nngp').block_until_ready()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "colab": {
          "height": 35
        },
        "colab_type": "code",
        "executionInfo": {
          "elapsed": 1829,
          "status": "ok",
          "timestamp": 1587514332112,
          "user": {
            "displayName": "",
            "photoUrl": "",
            "userId": ""
          },
          "user_tz": 420
        },
        "id": "y63mVmRdJmrD",
        "outputId": "61a32363-6dee-48a2-e59a-0c45888d6a9d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "1 loops, best of 3: 39.4 ms per loop\n"
          ]
        }
      ],
      "source": [
        "%%timeit\n",
        "ktd = ker_fn(input_x2, input_x1, 'nngp').block_until_ready()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "colab": {
          "height": 35
        },
        "colab_type": "code",
        "executionInfo": {
          "elapsed": 1937,
          "status": "ok",
          "timestamp": 1587514334072,
          "user": {
            "displayName": "",
            "photoUrl": "",
            "userId": ""
          },
          "user_tz": 420
        },
        "id": "AYEMMuzZy3SB",
        "outputId": "b653be82-ef26-4cdb-a288-bb7225b866b6"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "1 loops, best of 3: 53.5 ms per loop\n"
          ]
        }
      ],
      "source": [
        "# Compute NNGP and NTK \n",
        "%%timeit\n",
        "kdd = ker_fn(input_x1, None, ('nngp', 'ntk'))\n",
        "kdd.nngp.block_until_ready()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "r8VHnxBUuIKG"
      },
      "source": [
        "Using NT's batching funtion"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "Yr5dQsQktW0k"
      },
      "outputs": [],
      "source": [
        "_, _, ker_fn = MyrtleNetwork(5)\n",
        "ker_fn = nt.utils.batch.batch(ker_fn, batch_size=10)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "oTCU_kRpuT2c"
      },
      "outputs": [],
      "source": [
        "input_x = random.normal(key, shape=(50, 32, 32, 3))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "colab": {
          "height": 35
        },
        "colab_type": "code",
        "executionInfo": {
          "elapsed": 5725,
          "status": "ok",
          "timestamp": 1587514340925,
          "user": {
            "displayName": "",
            "photoUrl": "",
            "userId": ""
          },
          "user_tz": 420
        },
        "id": "IsxakS93uVdN",
        "outputId": "1682836e-1b7f-4343-bb1c-44368142513f"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "1 loops, best of 3: 991 ms per loop\n"
          ]
        }
      ],
      "source": [
        "# Note that library computes the full matrix thus lead to 2x inefficiency.\n",
        "# With custom batching, only compute upper triangles.\n",
        "# First loop during timing run includes jit compilation time and maybe slower.\n",
        "%%timeit\n",
        "kdd = ker_fn(input_x, None, 'nngp').block_until_ready()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "colab": {
          "height": 35
        },
        "colab_type": "code",
        "executionInfo": {
          "elapsed": 7755,
          "status": "ok",
          "timestamp": 1587514348695,
          "user": {
            "displayName": "",
            "photoUrl": "",
            "userId": ""
          },
          "user_tz": 420
        },
        "id": "aBOyHaCOwE6F",
        "outputId": "b69dbbbf-2371-40f7-a0a3-5e6bc3c991d6"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "1 loops, best of 3: 1.44 s per loop\n"
          ]
        }
      ],
      "source": [
        "# Compute NNGP and NTK \n",
        "%%timeit\n",
        "kdd = ker_fn(input_x, None, ('nngp', 'ntk'))\n",
        "kdd.nngp.block_until_ready()"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "last_runtime": {
        "build_target": "//learning/deepmind/dm_python:dm_notebook3",
        "kind": "private"
      },
      "name": "myrtle_kernel_with_neural_tangents.ipynb",
      "provenance": [
        {
          "file_id": "1v0PBYuy9ZJD6ZKQpe-YvSulCDwHh968r",
          "timestamp": 1587514143698
        }
      ]
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
